﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Core.Models;

namespace Core.Controllers
{
    public class MainMenuController : Controller
    {
        //
        // GET: /MainMenu/

        [Permission("Can Modify Domain")]
        public ActionResult Index()
        {
            return View();
        }

        //
        // POST: /BusinessUnit/BUList/

        [HttpPost]
        [Permission("Can Modify Domain")]
        public JsonResult MenuList(FormCollection collection)
        {
            CoreEntities core = new CoreEntities();
            Guid DomainId = (Guid)Session["DomainId"];
            int SkipRecs = int.Parse(collection.GetValues("iDisplayStart")[0].ToString());
            int TakeCount = int.Parse(collection.GetValues("iDisplayLength")[0].ToString());
            string strSearch = collection.GetValues("sSearch")[0].ToString();
            DataTableResponse r = new DataTableResponse();
            // Needs update when sorting is implemented
            List<MainMenu> list = core.MainMenus.Where(m => (m.Name.Contains(strSearch) && m.IsDroppedYN == "N" && m.DomainId == DomainId)).OrderBy(m => m.Sequence).ThenBy(m => m.Name).Skip(SkipRecs).Take(TakeCount).ToList();
            r.sEcho = collection.GetValues("sEcho")[0].ToString();
            // This query is required because the earlier query returns results for only 1 page.
            r.iTotalRecords = core.MainMenus.Where(m => (m.Name.Contains(strSearch) && m.IsDroppedYN == "N" && m.DomainId == DomainId)).Count();
            r.iTotalDisplayRecords = r.iTotalRecords;
            foreach (MainMenu m in list)
            {
                List<string> r1 = new List<string>();
                string editurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"editlink\" title=\"{1}\" >Edit</a>", "MainMenu", "Edit", m.MenuItemId.ToString());
                string detailsurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"detailslink\" title=\"{1}\" >Details</a>", "MainMenu", "Details", m.MenuItemId.ToString());
                string deleteurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"deletelink\" title=\"{1}\" >Delete</a>", "MainMenu", "Delete", m.MenuItemId.ToString());
                r1.Add(editurl + detailsurl + deleteurl);
                r1.Add(m.Name);
                r1.Add(m.URL);
                r1.Add(m.Sequence.ToString());
/*                r1.Add(String.Format("{0:g}", m.ModifiedDT));
                r1.Add(m.ModifiedByName); */
                r.aaData.Add(r1);
            }
            return Json(r);
        }

        //
        // GET: /MainMenu/Create

        [Permission("Can Modify Domain")]
        public ActionResult Create()
        {
            CoreEntities core = new CoreEntities();
            MainMenu menu = new MainMenu();
            menu.MenuItemId = Guid.NewGuid();
            menu.DomainId = (Guid)Session["DomainId"];
            List<Permission> plist = core.Permissions.ToList();
            ViewBag.PermissionList = plist;
            return View(menu);
        } 

        //
        // POST: /MainMenu/Create

        [HttpPost]
        [Permission("Can Modify Domain")]
        public ActionResult Create(MainMenu menu, FormCollection collection)
        {
            CoreEntities core = new CoreEntities();
            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    menu.IsDroppedYN = "N";
                    menu.CreateDT = DateTime.Now;
                    menu.CreatedById = (Guid)Session["UserId"];
                    menu.CreatedByName = Session["UserFullName"].ToString();
                    menu.ModifiedDT = DateTime.Now;
                    menu.ModifiedById = (Guid)Session["UserId"];
                    menu.ModifiedByName = Session["UserFullName"].ToString();
                    core.AddToMainMenus(menu);
                    core.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", Tools.ExceptionMessage(e));
            }
            List<Permission> plist = core.Permissions.ToList();
            ViewBag.PermissionList = plist;
            return View(menu);
        }
        
        //
        // GET: /MainMenu/Edit/5

        [Permission("Can Modify Domain")]
        public ActionResult Edit(Guid id)
        {
            CoreEntities core = new CoreEntities();
            MainMenu menu = core.MainMenus.First(m => m.MenuItemId == id);
            List<Permission> plist = core.Permissions.ToList();
            ViewBag.PermissionList = plist;
            return View(menu);
        }

        //
        // POST: /MainMenu/Edit/5

        [HttpPost]
        [Permission("Can Modify Domain")]
        public ActionResult Edit(MainMenu menu, FormCollection collection)
        {
            CoreEntities core = new CoreEntities();
            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    MainMenu nm = core.MainMenus.First(m => m.MenuItemId == menu.MenuItemId);
                    nm.Name = menu.Name;
                    nm.URL = menu.URL;
                    nm.UserPermission = menu.UserPermission;
                    nm.Sequence = menu.Sequence;
                    nm.HideOnSmallDevice = menu.HideOnSmallDevice;
                    nm.ModifiedDT = DateTime.Now;
                    nm.ModifiedById = (Guid)Session["UserId"];
                    nm.ModifiedByName = Session["UserFullName"].ToString();
                    core.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", Tools.ExceptionMessage(e));
            }
            List<Permission> plist = core.Permissions.ToList();
            ViewBag.PermissionList = plist;
            return View(menu);
        }

        //
        // GET: /MainMenu/Details/5

        [Permission("Can Modify Domain")]
        public ActionResult Details(Guid id)
        {
            CoreEntities core = new CoreEntities();
            MainMenu menu = core.MainMenus.First(m => m.MenuItemId == id);
            return View(menu);
        }

        //
        // GET: /MainMenu/Delete/5

        [Permission("Can Modify Domain")]
        public ActionResult Delete(Guid id)
        {
            CoreEntities core = new CoreEntities();
            MainMenu menu = core.MainMenus.First(m => m.MenuItemId == id);
            return View(menu);
        }

        //
        // POST: /MainMenu/Delete/5

        [HttpPost]
        [Permission("Can Modify Domain")]
        public ActionResult Delete(Guid id, FormCollection collection)
        {
            CoreEntities core = new CoreEntities();
            MainMenu menu;
            try
            {
                // TODO: Add delete logic here
                if (ModelState.IsValid)
                {
                    menu = core.MainMenus.First(m => m.MenuItemId == id);
                    menu.IsDroppedYN = "Y";
                    menu.ModifiedDT = DateTime.Now;
                    menu.ModifiedById = (Guid)Session["UserId"];
                    menu.ModifiedByName = Session["UserFullName"].ToString();
                    core.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch(Exception e)
            {
                ModelState.AddModelError("", Tools.ExceptionMessage(e));
            }
            menu = core.MainMenus.First(m => m.MenuItemId == id);
            return View(menu);
        }

        //
        // GET: /MainMenu/Display
        [ChildActionOnly]
        public ActionResult Display()
        {
            List<MainMenu> list;
            if ((bool)Session["IsValid"])
            {
                Guid DomainId = (Guid)Session["DomainId"];
                CoreEntities core = new CoreEntities();
                list = core.MainMenus.Where(m => (m.DomainId == DomainId && m.IsDroppedYN == "N")).OrderBy(m => m.Sequence).ThenBy(m => m.Name).ToList();
            }
            else
            {
                list = new List<MainMenu>();
            }
            return PartialView(list);
        }
    }
}
